<template>
	<view class="content">
		<scroll-view refresher-enabled="true" @refresherrefresh="onDownRefresh" style="height: 100%"
			:refresher-triggered="isRefreshing" @scrolltolower="loadMore" :onLoadmore="false" scroll-y="true">
			<view class="listBox">
				<view class="list" v-for="(item, index) in data.dataList" :key="item.id">
					<view class="info flex" style="justify-content: space-between;" @click.native.stop="goDetail(item)">
						<view class="address">{{item.apartmentName|| '--'}}{{item.roomName|| '--'}}</view>
						<uni-icons class="icon" type="forward" size="18" color="#6A6A6A"></uni-icons>
					</view>
					<view>
						<view class="intro flex">
							<view class="tit">合同周期：</view>
							<view class="txt flex-1 text-right">
								{{timestamp(item.startTime)|| '--'}}-{{timestamp(item.endTime)|| '--'}}</view>
						</view>
						<view class="intro flex">
							<view class="tit">租客名称：</view>
							<view class="txt flex-1 text-right">{{item.customerName|| '--'}}</view>
						</view>
						<view class="intro flex">
							<view class="tit">租金：</view>
							<view class="txt flex-1 text-right"><text class="yellow">{{item.monthRent|| '--'}}元</text>/月
							</view>
						</view>
						<view class="intro flex">
							<view class="tit">时间：</view>
							<view class="txt flex-1 text-right">{{timestamp(item.createTime,'s')|| '--'}}</view>
						</view>
						<view class="status">
							<view :class="{
									'green':['check_in','active'].includes(item.contractStatus),
									'blue':['active','no_signed'].includes(item.contractStatus)}">{{computedStatus(item.contractStatus)}}</view>
						</view>
					</view>
					<view class="btn center" v-if="item.contractStatus != 'lost_effectiveness'">
						<text class="yellow"
							v-if="item.contractStatus == 'no_signed'&&item.signStatus == 'signed_party_b'"
							@click.native.stop="goSign(item)">在线签约</text>
						<text class="yellow" v-if="['check_in','active'].includes(item.contractStatus)"
							@click.native.stop="downLoadContract(item)">下载电子合同</text>
					</view>
				</view>
				<view v-if="!data.dataList || data.dataList&&data.dataList.length == 0" class="flex-b">
					<u-empty mode="data" icon="https://www.mescroll.com/img/mescroll-empty.png"></u-empty>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script setup lang="ts">
	import { getLandlordContractList, downLoadLandlordElectronic } from '@/common/API/contract'
	import { onShow, onLoad, onUnload } from "@dcloudio/uni-app"
	import { reactive, ref } from "vue";
	import dayjs from "dayjs"
	import config from '@/utils/config'

	const data = reactive({
		dataList: []
	})
	const flag = ref(false)
	const form = reactive({
		pageSize: 10,
		pageNo: 1,
		page: 0,
		checkItem: null
	})
	const isRefreshing = ref(false)
	const isLoadMore = ref(false)

	const getList = async () => {
		uni.showLoading({
			title: '加载中...'
		});
		let res = await getLandlordContractList(form.pageSize, form.pageNo)
		console.log(res)
		uni.hideLoading()
		form.page = res.total ? Math.ceil(res.total / form.pageSize) : 1
		if (res) {
			data.dataList = [...data.dataList, ...res.list]
		}
	}
	const goDetail = (item) => {
		uni.navigateTo({
			url: `/pages/personal/landlord/ownerDetail?id=${item.id}`
		})
	}
	//在线签约
	const goSign = (item) => {
		let userInfo = uni.getStorageSync('userInfo')
		if (!userInfo.authenticated) {
			uni.showToast({
				title: '用户未实名认证',
				icon: 'none',
			});
			return
		}
		// #ifdef APP-PLUS  
		console.log("plus");

		plus.share.getServices(function (res) {
			var sweixin = null;
			for (var i = 0; i < res.length; i++) {
				var t = res[i];
				if (t.id == 'weixin') {
					sweixin = t;
				}
			}
			console.log(JSON.stringify(sweixin))
			let loginInfo = {
				userPhone: uni.getStorageSync('userPhone'),
				accessToken: uni.getStorageSync('accessToken'),
				userId: uni.getStorageSync('userId'),
				tenentId: uni.getStorageSync('tenentId')
			}
			if (sweixin) {
				sweixin.launchMiniProgram({
					id: config.wxChatAppId,
					type: config.type,
					path: `/pages/internal/index?loginInfo=${encodeURIComponent(JSON.stringify(loginInfo))}&url=${encodeURIComponent(`/pages/personal/landlord/ownerSign?id=${item.id}&phone=${item.customerPhone}`)}`
				});
			}
		}, function (e) {
			console.log();
		});
		//#endif	
		// #ifndef APP-PLUS
		uni.redirectTo({
			url: `/pages/personal/landlord/ownerSign?id=${item.id}&phone=${item.customerPhone}`
		})
		// #endif
	}
	//状态
	const computedStatus = (val : string) => {
		switch (val) {
			case 'pending':
				return '待审批'
			case 'no_signed':
				return '待签约'
			case 'active':
				return '已生效'
			case 'abnormal_end':
				return '非正常结束'
			case 'check_in':
				return '已入住'
			case 'reject':
				return '审批驳回'
			case 'normal_end':
				return '正常结束'
			case 'nullify':
				return '合同作废'
			case 'lost_effectiveness':
				return '已失效'
			default:
				return '--'
		}
	}
	onShow(() => {
		form.pageNo = 1
		form.pageSize = 10
		data.dataList = [];
		getList()
	})
	onLoad((options) => {
		if (options) {
			flag.value = options.flag
		}
	})
	const onDownRefresh = () => {
		data.dataList = []
		console.log('下拉刷新')
		form.pageNo = 1
		form.pageSize = 10
		isRefreshing.value = true;
		getList()
		setTimeout(() => {
			isRefreshing.value = false;
			uni.stopPullDownRefresh()
		}, 800)
	}
	const loadMore = () => {
		console.log('上拉加载更多')
		if (form.pageNo > form.page) {
			return
		}
		form.pageNo++
		isLoadMore.value = true;
		getList()
		setTimeout(() => {
			isLoadMore.value = false;
		}, 2000)
	}
	//处理时间戳
	const timestamp = (val : any, s) => {
		return val ? (!s ? dayjs(val).format('YYYY-MM-DD') : dayjs(val).format('YYYY-MM-DD HH:mm:ss')) : '--'
	}
	onUnload(() => {
		console.log('onUnload')
		if (!flag.value) {
			uni.navigateTo({
				url: '/pages/personal/landlord/index',
			})
		}
	})
	//下载电子合同
	const downLoadContract = async (item) => {
		let p = await downLoadLandlordElectronic(item.id)
		if (p) {
			// #ifdef MP-WEIXIN
			uni.downloadFile({
				url: p.downloadUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							success: (res1) => {
								var savedFilePath = res1.savedFilePath;
								if (savedFilePath) {
									wx.openDocument({
										filePath: res1.savedFilePath,
										showMenu: true,
										fileType: "pdf",
										success: function (res2) {
											console.log('打开PDF成功');
										},
										fail: function (err) {
											console.log(err)
										}
									})
								}
							}, fail: err2 => {
								console.log(err2)
							}
						})
					}
				},
				fail: (err1) => {
					console.log(err1)
				}
			});
			// #endif	
			// #ifdef APP-PLUS
			uni.downloadFile({
				url: p.downloadUrl,
				success: res => {
					console.log(res)
					if (res.statusCode === 200) {
						uni.saveFile({
							tempFilePath: res.tempFilePath,
							success: res2 => {
								uni.openDocument({
									filePath: res2.savedFilePath,
									showMenu: true,
									fileType: "pdf",
									success: function (res3) {
										console.log('打开PDF成功');
									},
									fail: function (err) {
										if (err.errCode == 1 || err.code == 1) {
											// uni.showToast({
											// 	title: `未找到能打开PDF类型文件的手机应用`,
											// 	icon: 'none'
											// })
											
											//查看合同 打开webview
											uni.navigateTo({
												url: `/pages/personal/contract/web-view?url=${encodeURIComponent(p.downloadUrl)}`
											})
										}
									}
								})
							},
							fail: e => {
								console.log(e)
								uni.showToast({
									title: "保存失败，请稍后重试！",
									icon: "none"
								})
							}
						})
					}
				}, fail: err => {
					console.log(err)
				}
			})
			// #endif
		}
	}
</script>
<style>
	page {
		height: 100%;
	}
</style>
<style lang="scss" scoped>
	.content {
		.listBox {
			padding: 24rpx 32rpx;

			.list {
				background: #fff;
				margin: 0 0 24rpx;
				border-radius: 8rpx;
				padding: 36rpx 32rpx 0;
				box-shadow: 0px 0px 16px rgb(255, 255, 255, 0.08);

				.info {
					margin: 0 0 20rpx;

					.address {
						font-weight: 400;
						font-size: 36rpx;
						line-height: 44rpx;
						width: 400rpx;
						text-overflow: ellipsis;
						white-space: nowrap;
						overflow: hidden;
						display: inline-block;
					}

					.icon {
						line-height: 44rpx;
					}
				}

				.intro {
					margin: 0 0 10rpx;

					.tit,
					.txt {
						color: #999;
						line-height: 44rpx;
					}
				}

				.status {
					color: #ccc;
					font-size: 32rpx;
					line-height: 38rpx;
					padding: 6rpx 0 24rpx;
				}

				.btn {
					border-top: 2rpx solid #E5E5E5;
					padding: 30rpx 0;
				}
			}
		}
	}

	.text-right {
		text-align: right;
	}

	.gray {
		color: rgba(204, 204, 204, 1)
	}

	.blue {
		color: rgba(49, 113, 232, 1);
	}

	.flex-b {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.status {
		display: flex;
		justify-content: space-between;

		.stay {
			color: rgba(253, 150, 24, 1);
		}
	}
</style>